<template>
  <div class="seal-container">
    <!-- 搜索栏 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="公章种类">
          <el-select v-model="searchForm.sealType" placeholder="请选择公章种类" clearable>
            <el-option label="全部" value="" />
            <el-option label="公章" value="official" />
            <el-option label="合同专用章" value="contract" />
            <el-option label="财务专用章" value="financial" />
            <el-option label="发票专用章" value="invoice" />
            <el-option label="法定代表人章" value="legal" />
          </el-select>
        </el-form-item>
        <el-form-item label="经办人">
          <el-input
            v-model="searchForm.handler"
            style="width: 180px"
            placeholder="请输入律师姓名"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="sealStore.loading">
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 错误提示 -->
    <el-alert
      v-if="sealStore.error"
      :title="sealStore.error"
      type="error"
      show-icon
      closable
      @close="sealStore.clearError"
      style="margin-bottom: 20px;"
    />

    <!-- 表格区域 -->
    <el-card>
      <div class="table-header">
        <h3>印章使用登记表</h3>
        <div>
          <el-button @click="refreshData" :loading="sealStore.loading">
            刷新
          </el-button>
          <el-button type="primary" @click="handleAdd">
            新增登记
          </el-button>
          <el-button type="success" @click="exportData">
            导出表格
          </el-button>
          <!-- 下载Word模板按钮 -->
          <el-button type="info" @click="downloadTemplate" :loading="downloadLoading">
            下载Word模板
          </el-button>
        </div>
      </div>

      <el-table :data="sealStore.sealRecords" style="width: 100%" v-loading="sealStore.loading">
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column prop="date" label="使用日期" width="140">
          <template #default="{ row }">
            {{ formatDate(row.date) }}
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="使用原因" show-overflow-tooltip />
        <el-table-column prop="copies" label="份数" width="80" />
        <el-table-column prop="sealType" label="公章种类" width="120">
          <template #default="{ row }">
            <el-tag :type="getSealTypeTagType(row.sealType)">
              {{ getSealTypeName(row.sealType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handler" label="经办人" width="120" />
        <el-table-column prop="remarks" label="备注" width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="sealStore.pagination.page"
        v-model:page-size="sealStore.pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="sealStore.pagination.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增印章使用登记' : '编辑印章使用登记'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="使用日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="请选择使用日期"
            style="width: 100%"
            required
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="使用原因" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入使用原因"
          />
        </el-form-item>
        <el-form-item label="份数" prop="copies">
          <el-input
            v-model.number="form.copies"
            type="number"
            min="1"
            placeholder="请输入份数"
          />
        </el-form-item>
        <el-form-item label="公章种类" prop="sealType">
          <el-select v-model="form.sealType" placeholder="请选择公章种类">
            <el-option label="公章" value="official" />
            <el-option label="合同专用章" value="contract" />
            <el-option label="财务专用章" value="financial" />
            <el-option label="发票专用章" value="invoice" />
            <el-option label="法定代表人章" value="legal" />
          </el-select>
        </el-form-item>
        <el-form-item label="经办人" prop="handler">
          <el-input
            v-model="form.handler"
            placeholder="请输入经办人（律师）姓名"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmSubmit"
            :loading="submitLoading"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useSealStore } from "@/store/sealStore";
import { ElMessage, ElMessageBox } from 'element-plus'
import { sealService } from '@/api/seal';

// 初始化store实例
const sealStore = useSealStore()

// 模板下载加载状态
const downloadLoading = ref(false)

// 获取当前登录用户
const currentUser = ref('admin')

// 搜索表单
const searchForm = reactive({
  dateRange: [],
  sealType: '',
  handler: ''
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 edit
const currentRecord = ref(null)
const submitLoading = ref(false)
const formRef = ref(null)

// 表单数据和验证规则
const form = reactive({
  date: new Date(),
  reason: '',
  copies: 1,
  sealType: '',
  handler: '',
  remarks: ''
})

const rules = {
  date: [{ required: true, message: '请选择使用日期', trigger: 'change' }],
  reason: [{ required: true, message: '请输入使用原因', trigger: 'blur' }],
  copies: [
    { required: true, message: '请输入份数', trigger: 'blur' },
    { type: 'number', min: 1, message: '份数必须大于0', trigger: 'blur' }
  ],
  sealType: [{ required: true, message: '请选择公章种类', trigger: 'change' }],
  handler: [{ required: true, message: '请输入经办人', trigger: 'blur' }]
}

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString()
}

// 转换公章类型为显示文本
const getSealTypeName = (type) => {
  const typeMap = {
    'official': '公章',
    'contract': '合同专用章',
    'financial': '财务专用章',
    'invoice': '发票专用章',
    'legal': '法定代表人章'
  }
  return typeMap[type] || type
}

// 根据公章类型获取标签样式
const getSealTypeTagType = (type) => {
  const typeMap = {
    'official': 'primary',
    'contract': 'success',
    'financial': 'warning',
    'invoice': 'info',
    'legal': 'danger'
  }
  return typeMap[type] || 'info'
}

// 搜索操作
const handleSearch = () => {
  sealStore.searchSealRecords(searchForm)
}

// 重置搜索条件
const resetSearch = () => {
  searchForm.dateRange = []
  searchForm.sealType = ''
  searchForm.handler = ''
  sealStore.searchSealRecords(searchForm)
}

// 刷新数据
const refreshData = () => {
  sealStore.fetchSealRecords({
    page: sealStore.pagination.page,
    pageSize: sealStore.pagination.pageSize
  })
}

// 分页页码变更
const handlePageChange = (page) => {
  sealStore.changePage(page)
}

// 每页条数变更
const handleSizeChange = (size) => {
  sealStore.changePageSize(size)
}

// 打开新增对话框
const handleAdd = () => {
  dialogType.value = 'add'
  currentRecord.value = null
  // 重置表单
  Object.assign(form, {
    date: new Date(),
    reason: '',
    copies: 1,
    sealType: '',
    handler: '',
    remarks: ''
  })
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogType.value = 'edit'
  currentRecord.value = row
  // 填充表单数据
  Object.assign(form, {
    date: row.date ? new Date(row.date) : new Date(),
    reason: row.reason || '',
    copies: row.copies || 1,
    sealType: row.sealType || '',
    handler: row.handler || '',
    remarks: row.remarks || ''
  })
  dialogVisible.value = true
}

// 删除记录
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const success = await sealStore.deleteSealRecord(row.id)
    if (success) {
      ElMessage.success('删除成功')
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error(err.message || '删除失败')
    }
  }
}

// 提交表单（新增/编辑）
const confirmSubmit = async () => {
  // 表单验证
  await formRef.value.validate()

  try {
    submitLoading.value = true

    if (dialogType.value === 'add') {
      const success = await sealStore.addSealRecord(form, currentUser.value)
      if (success) {
        ElMessage.success('新增成功')
        dialogVisible.value = false
      }
    } else {
      const success = await sealStore.updateSealRecord(currentRecord.value.id, form, currentUser.value)
      if (success) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
      }
    }
  } catch (err) {
    ElMessage.error(err.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 导出Excel
const exportData = async () => {
  try {
    // 构建查询参数
    const params = {
      sealType: searchForm.sealType,
      handler: searchForm.handler
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }

    // 调用导出接口
    const response = await sealService.exportExcel(params)

    // 处理二进制流
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `印章使用登记表_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`
    document.body.appendChild(link)
    link.click()

    // 清理资源
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (err) {
    console.error('导出失败:', err)
    ElMessage.error(`导出失败: ${err.response?.data?.msg || '服务器错误'}`)
  }
}

// 下载Word模板
const downloadTemplate = async () => {
  try {
    downloadLoading.value = true

    // 调用后端下载模板接口
    const response = await sealService.downloadTemplate()

    // 处理二进制流
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    })

    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '印章使用登记模板.docx'
    document.body.appendChild(link)
    link.click()

    // 清理资源
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('模板下载成功')
  } catch (err) {
    console.error('模板下载失败:', err)
    ElMessage.error(`模板下载失败: ${err.response?.data?.msg || '服务器错误'}`)
  } finally {
    downloadLoading.value = false
  }
}

// 页面挂载时加载数据
onMounted(() => {
  sealStore.fetchSealRecords()
})
</script>

<style scoped>
.seal-container {
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.filter-card {
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table .el-tag) {
  margin: 0 2px;
}

:deep(.el-form-item) {
  margin-right: 15px;
}

.dialog-footer {
  text-align: right;
}
</style>
